export const UserModel = {
  async findByEmail(env, email) {
    try {
      const stmt = env.DB.prepare('SELECT * FROM users WHERE email = ?')
      const result = await stmt.bind(email).first()
      return result
    } catch (error) {
      console.error('查询用户失败:', error)
      // 返回 null 而不是抛出错误，让调用者处理
      return null
    }
  },

  async create(env, { email, authKey, authSalt, encryptSalt, masterKey, masterKeyIv }) {
    try {
      const stmt = env.DB.prepare(
        'INSERT INTO users (email, auth_key, auth_salt, encrypt_salt, master_key, master_key_iv) VALUES (?, ?, ?, ?, ?, ?)'
      )
      return await stmt.bind(email, authKey, authSalt, encryptSalt, masterKey, masterKeyIv).run()
    } catch (error) {
      console.error('创建用户失败:', error)
      throw error
    }
  },

  async update(env, id, data) {
    try {
      const sets = []
      const values = []
      
      if (data.authKey) {
        sets.push('auth_key = ?')
        values.push(data.authKey)
      }

      if (data.authSalt) {
        sets.push('auth_salt = ?')
        values.push(data.authSalt)
      }

      if (data.encryptSalt) {
        sets.push('encrypt_salt = ?')
        values.push(data.encryptSalt)
      }

      if (data.masterKey) {
        sets.push('master_key = ?')
        values.push(data.masterKey)
      }
      
      if (data.masterKeyIv) {
        sets.push('master_key_iv = ?')
        values.push(data.masterKeyIv)
      }
      
      if (sets.length === 0) return null
      
      values.push(id)
      const query = `UPDATE users SET ${sets.join(', ')}, updated_at = DATETIME('now') WHERE id = ?`
      
      const stmt = env.DB.prepare(query)
      return await stmt.bind(...values).run()
    } catch (error) {
      console.error('更新用户失败:', error)
      throw error
    }
  }
} 